import { Layout, Menu } from "antd";
import { Content, Header } from "antd/es/layout/layout";
import Sider from "antd/es/layout/Sider";
import styles from "./Index.module.less";
import { Outlet, useLocation, useNavigate } from "react-router-dom";
import { useEffect, useState } from "react";
import logo from "@/assets/images/public/logo.jpg";
import { useSelector } from "react-redux";
import type { RootState } from "@/store";
import FontIcon from "@/components/public/fontIcon/Index";
import type { ItemType } from "antd/es/menu/interface";
import { deepCloneOverall } from "@/utils/tool";
import LayoutHeader from "./components/layoutHeader/Index";

export default function index() {
  let [menus, setMenus] = useState(deepCloneOverall(useSelector((state: RootState) => state.menu.menus)));

  const navigate = useNavigate();
  // 注意：用动态 import，返回值是模块对象，需要 .default 取出 url
  const collapsed = useSelector((state: RootState) => state.menu.collapsed);
  const handleMenus = (menus: ItemType[]): ItemType[] => {
    return menus.map((item: any) => {
      if (item.children) {
        item.children = handleMenus(item.children);
      }
      return {
        ...item,
        icon: <FontIcon name={item.icon} size="18px" />,
      };
    });
  };

  useEffect(() => {
    setMenus(handleMenus(menus));
  }, []);

  const location = useLocation();
  const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
  const [openKeys, setOpenKeys] = useState<string[]>([]);
  useEffect(() => {
    if (location.pathname) {
      let pathname = location.pathname;
      setSelectedKeys([pathname]);
      // 父级展开项：逐层拼接路径
      const segments = pathname.split("/").filter(Boolean); // 去掉空字符串
      const parents = segments
        .slice(0, -1) // 不包含最后一个
        .map((_, i) => "/" + segments.slice(0, i + 1).join("/"));

      setOpenKeys(parents);
    }
  }, [location.pathname]);

  return (
    <>
      <Layout className={styles.layout}>
        <Sider width={collapsed ? "64px" : "260px"}>
          <div className={styles.sider_logo} onClick={() => navigate("/")}>
            <img className={styles.logo} src={logo} alt="logo" />
            {!collapsed ? <h1 className={styles.title}>后台管理系统</h1> : null}
          </div>
          <Menu
            className="u-scrollbar"
            selectedKeys={selectedKeys}
            openKeys={openKeys}
            mode="inline"
            inlineCollapsed={collapsed}
            items={menus}
            onClick={(e) => navigate(e.key)}
            onOpenChange={(keys) => setOpenKeys(keys)}
          />
        </Sider>
        <Layout>
          <Header>
            <LayoutHeader />
          </Header>
          <Content>
            <Outlet />
          </Content>
        </Layout>
      </Layout>
    </>
  );
}
